package com.chase.passwordmaster.pass

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.chase.passwordmaster.R
import com.chase.passwordmaster.data.GlobalData
import com.chase.passwordmaster.encoder.encoder_v2.generateAndSaveRSAKeyByLoginPass
import com.chase.passwordmaster.entity.EncodedLoginPassword
import com.chase.passwordmaster.main.MainActivity
import com.chase.passwordmaster.utils.BCrypt
import com.chase.passwordmaster.utils.showToast
import com.chase.passwordmaster.utils.useDarkStatusBar

class SetPassActivity : AppCompatActivity() {

    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, SetPassActivity::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var cpInputPass: EditText
    private lateinit var cpSetPass: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_set_pass)

        cpInputPass = findViewById(R.id.input_pass_set_pass)
        cpSetPass = findViewById(R.id.set_pass_set_pass)

        useDarkStatusBar()

        initCPSetPass()
    }

    private fun initCPSetPass() {
        cpSetPass.setOnClickListener {
            val pass = cpInputPass.text.toString()
            if (pass.isNotBlank()) {
                if (!encryptAndSaveLoginPassword(pass)) {
                    showToast("保存密码失败")
                    Log.i("GSC", "Save pass fail in SetPassActivity")
                }
                GlobalData.loginPassword
                    ?.let {
                        // Generate and save RSA key pair by login pass
                        if (generateAndSaveRSAKeyByLoginPass(loginPass = it)) {
                            // Jump
                            MainActivity.actionStart(this, it)
                            this.finish()
                        } else {
                            showToast("程序错误")
                            Log.i("GSC:", "loginPass可读取，生成RSA密钥失败")
                        }
                    }
                    ?: showToast("密码已设置，未知错误程序无法访问新设密码", Toast.LENGTH_LONG)
            } else {
                showToast("密码不能为空")
            }
        }
    }
}

/**
 * Encrypt and save login password (pass)
 * If encryptedLoginPasswordObject in GlobalData does not exist,
 * Create a new EncodedLoginPassword instance and assign,
 * Else change its attributed encodedLoginPassword and call save()
 * to refresh.
 * @param pass plaint pass text
 * @return success to save?
 */
fun encryptAndSaveLoginPassword(pass: String): Boolean {
    val encryptedPass = BCrypt.hashpw(pass, BCrypt.gensalt())
    var success = false
    GlobalData.loginPassword = pass
    if (GlobalData.encryptedLoginPasswordObject == null) {
        GlobalData.encryptedLoginPasswordObject = EncodedLoginPassword(encryptedPass).also { success = it.save() }
    } else {
        GlobalData.encryptedLoginPasswordObject?.apply {
            encodedLoginPassword = encryptedPass
            success = save()
        }
    }
    return success
}